<template>
  <div class="system-bg">
    <el-card class="user-card" shadow="hover">
      <div slot="header" class="card-header-horizontal">
        <div class="header-title">提交成员审核</div>
        <div class="header-btn-group">
          <el-button class="back-btn" @click="$router.go(-1)">返回</el-button>
        </div>
      </div>

      <el-form
        ref="auditForm"
        :model="form"
        :rules="rules"
        label-width="120px"
        class="audit-form"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属家族" prop="clanId">
              <el-select v-model="form.clanId" placeholder="请选择家族" clearable class="full-width">
                <el-option v-for="clan in clanList" :key="clan.id" :label="clan.name" :value="clan.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关系类型" prop="relationship">
              <el-select v-model="form.relationship" placeholder="请选择关系类型" clearable class="full-width">
                <el-option label="子女" value="CHILD" />
                <el-option label="配偶" value="SPOUSE" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="成员姓名" prop="name">
              <el-input v-model="form.name" placeholder="请输入成员姓名" class="full-width" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="form.gender">
                <el-radio label="M">男</el-radio>
                <el-radio label="F">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="出生日期" prop="birthDate">
              <el-date-picker
                v-model="form.birthDate"
                type="date"
                placeholder="选择出生日期"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                class="full-width"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="去世日期" prop="deathDate">
              <el-date-picker
                v-model="form.deathDate"
                type="date"
                placeholder="选择去世日期"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                class="full-width"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="关联成员" prop="parentId">
              <el-select 
                v-model="form.parentId" 
                placeholder="请选择关联成员" 
                clearable 
                filterable
                class="full-width"
                @change="handleParentChange"
              >
                <el-option v-for="member in memberList" :key="member.id" :label="member.name" :value="member.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="籍贯" prop="nativePlace">
              <el-cascader
                v-model="form.nativePlace"
                :options="regionOptions"
                placeholder="请选择籍贯"
                class="full-width"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="现住地址" prop="currentAddress">
          <el-input v-model="form.currentAddress" placeholder="请输入现住地址" />
        </el-form-item>

        <el-form-item label="个人照片" prop="photo">
          <el-upload
            class="photo-uploader"
            :action="uploadUrl"
            :headers="uploadHeaders"
            :show-file-list="false"
            :on-success="handlePhotoSuccess"
            :before-upload="beforePhotoUpload"
            :on-error="handlePhotoError"
          >
            <img v-if="form.photo" :src="form.photo" class="photo-preview" />
            <i v-else class="el-icon-plus photo-uploader-icon"></i>
          </el-upload>
          <div class="upload-tip">建议上传JPG、PNG格式，大小不超过2MB</div>
        </el-form-item>

        <el-form-item label="个人事迹" prop="story">
          <el-input
            v-model="form.story"
            type="textarea"
            :rows="4"
            placeholder="请输入个人事迹"
          />
        </el-form-item>

        <el-form-item>
          <div class="form-actions">
            <el-button type="primary" @click="handleSubmit" :loading="submitting" class="submit-btn">提交审核</el-button>
            <el-button @click="handleReset" class="reset-btn">重置</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { submitAudit } from '@/api/audit';
import { getClanList } from '@/api/clan';
import { getMemberList } from '@/api/member';
import { getRegionTree } from '@/api/region';

export default {
  name: 'AuditSubmit',
  data() {
    return {
      submitting: false,
      clanList: [],
      memberList: [],
      regionOptions: [],
      form: {
        clanId: null,
        relationship: '',
        name: '',
        gender: '',
        birthDate: '',
        deathDate: '',
        parentId: null,
        nativePlace: [],
        currentAddress: '',
        photo: '',
        story: ''
      },
      rules: {
        clanId: [
          { required: true, message: '请选择所属家族', trigger: 'change' }
        ],
        relationship: [
          { required: true, message: '请选择关系类型', trigger: 'change' }
        ],
        name: [
          { required: true, message: '请输入成员姓名', trigger: 'blur' },
          { min: 2, max: 20, message: '姓名长度在2到20个字符', trigger: 'blur' }
        ],
        gender: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ],
        parentId: [
          { required: true, message: '请选择关联成员', trigger: 'change' }
        ]
      },
      uploadUrl: process.env.VUE_APP_BASE_API + '/api/v1/upload/member-photo',
      uploadHeaders: {
        Authorization: 'Bearer ' + localStorage.getItem('token')
      }
    };
  },
  created() {
    this.loadData();
  },
  methods: {
    async loadData() {
      await Promise.all([
        this.getClanList(),
        this.getMemberList(),
        this.getRegionTree()
      ]);
    },

    async getClanList() {
      try {
        const response = await getClanList();
        if (response.code === 0) {
          this.clanList = response.data;
        }
      } catch (error) {
        console.error('获取家族列表失败:', error);
      }
    },

    async getMemberList() {
      try {
        const response = await getMemberList({ page: 1, size: 1000 });
        if (response.code === 0) {
          this.memberList = response.data.records;
        }
      } catch (error) {
        console.error('获取成员列表失败:', error);
      }
    },

    async getRegionTree() {
      try {
        const response = await getRegionTree();
        if (response.code === 0) {
          this.regionOptions = response.data;
        }
      } catch (error) {
        console.error('获取地区树失败:', error);
      }
    },

    handleParentChange(parentId) {
      console.log('选择的关联成员:', parentId);
    },

    beforePhotoUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传照片只能是JPG或PNG格式!');
        return false;
      }
      if (!isLt2M) {
        this.$message.error('上传照片大小不能超过2MB!');
        return false;
      }
      return true;
    },

    handlePhotoSuccess(response, file) {
      if (response.code === 0) {
        this.form.photo = response.data;
        this.$message.success('照片上传成功');
      } else {
        this.$message.error(response.msg || '照片上传失败');
      }
    },

    handlePhotoError() {
      this.$message.error('照片上传失败');
    },

    async handleSubmit() {
      this.$refs.auditForm.validate(async (valid) => {
        if (valid) {
          this.submitting = true;
          try {
            const submitData = {
              ...this.form,
              proposerUserId: this.$store.state.user.id,
              nativePlace: this.form.nativePlace ? this.form.nativePlace.join(' ') : ''
            };

            const response = await submitAudit(submitData);
            if (response.code === 0) {
              this.$message.success('审核申请提交成功，请等待审核');
              this.$router.push('/audit');
            } else {
              this.$message.error(response.msg || '提交失败');
            }
          } catch (error) {
            console.error('提交审核失败:', error);
            this.$message.error('提交失败，请稍后重试');
          } finally {
            this.submitting = false;
          }
        }
      });
    },

    handleReset() {
      this.$refs.auditForm.resetFields();
      this.form.photo = '';
    }
  }
};
</script>

<style scoped>
.system-bg {
  min-height: 80vh;
  background: linear-gradient(135deg, #f4f6fa 60%, #e0e7ff 100%);
  display: flex;
  align-items: flex-start;
  justify-content: center;
  padding: 48px 0;
  animation: fadeIn 0.8s;
}

.user-card {
  width: 1100px;
  border-radius: 18px;
  box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.10);
  background: rgba(255,255,255,0.95);
  transition: box-shadow 0.3s;
}

.card-header-horizontal {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  padding-bottom: 8px;
}

.header-title {
  font-size: 22px;
  font-weight: bold;
  margin-bottom: 10px;
  text-align: left;
}

.header-btn-group {
  display: flex;
  align-items: center;
  background: none;
  border-radius: 0;
  padding: 0;
  box-shadow: none;
}

.header-btn-group .el-button {
  margin-right: 8px;
  height: 34px;
  font-size: 15px;
  padding: 0 18px;
  display: flex;
  align-items: center;
}

.header-btn-group .el-button:last-child {
  margin-right: 0;
}

.back-btn {
  background: #fff;
  border: 1px solid #909399;
  color: #606266;
  transition: all 0.2s;
}

.back-btn:hover {
  background: #f4f6fa;
  color: #409EFF;
  border-color: #409EFF;
}

.audit-form {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px 0;
}

.full-width {
  width: 100%;
}

.photo-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 8px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
  transition: all 0.3s;
}

.photo-uploader:hover {
  border-color: #6a82fb;
  box-shadow: 0 2px 8px rgba(106, 130, 251, 0.2);
}

.photo-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.photo-preview {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
  border-radius: 8px;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}

.form-actions {
  display: flex;
  gap: 16px;
  justify-content: center;
  margin-top: 32px;
}

.submit-btn {
  background: linear-gradient(90deg, #6a82fb 0%, #fc5c7d 100%);
  border: none;
  color: #fff;
  font-weight: bold;
  padding: 12px 32px;
  font-size: 16px;
  border-radius: 8px;
  transition: all 0.3s;
}

.submit-btn:hover {
  background: linear-gradient(90deg, #fc5c7d 0%, #6a82fb 100%);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(106, 130, 251, 0.3);
}

.reset-btn {
  background: #fff;
  border: 1px solid #909399;
  color: #606266;
  padding: 12px 32px;
  font-size: 16px;
  border-radius: 8px;
  transition: all 0.3s;
}

.reset-btn:hover {
  background: #f4f6fa;
  color: #409EFF;
  border-color: #409EFF;
  transform: translateY(-2px);
}

/* 表单样式 */
.el-form-item {
  margin-bottom: 24px;
}

.el-form-item__label {
  font-weight: 600;
  color: #606266;
  font-size: 14px;
}

.el-input__inner,
.el-select .el-input__inner,
.el-cascader .el-input__inner {
  border-radius: 6px;
  border: 1px solid #e4e7ed;
  transition: all 0.3s;
}

.el-input__inner:focus,
.el-select .el-input__inner:focus,
.el-cascader .el-input__inner:focus {
  border-color: #6a82fb;
  box-shadow: 0 0 0 2px rgba(106, 130, 251, 0.1);
}

.el-radio-group {
  display: flex;
  gap: 24px;
}

.el-radio {
  margin-right: 0;
}

.el-radio__label {
  font-weight: 500;
}

.el-textarea__inner {
  border-radius: 6px;
  border: 1px solid #e4e7ed;
  transition: all 0.3s;
}

.el-textarea__inner:focus {
  border-color: #6a82fb;
  box-shadow: 0 0 0 2px rgba(106, 130, 251, 0.1);
}

/* 日期选择器样式 */
.el-date-picker {
  width: 100%;
}

.el-date-editor.el-input {
  width: 100%;
}

/* 级联选择器样式 */
.el-cascader {
  width: 100%;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .audit-form {
    max-width: 100%;
    padding: 16px 0;
  }
  
  .el-form-item {
    margin-bottom: 20px;
  }
  
  .form-actions {
    flex-direction: column;
    gap: 12px;
  }
  
  .submit-btn,
  .reset-btn {
    padding: 10px 24px;
    font-size: 14px;
  }
  
  .photo-uploader {
    width: 150px;
    height: 150px;
  }
  
  .photo-uploader-icon {
    width: 150px;
    height: 150px;
    line-height: 150px;
  }
  
  .photo-preview {
    width: 150px;
    height: 150px;
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style> 